<?php

namespace app\traits;

use app\service\auth;
use Illuminate\Database\Capsule\Manager as DB;
use Illuminate\Database\Eloquent\Builder;

trait orderscope
{
    // 已失效
    public function scopeInvalid($query)
    {
        return $query->where('status', self::STATUS_INVALID);
    }

    // 已取消
    public function scopeCancel($query)
    {
        return $query->where('status', self::STATUS_CANCEL);
    }

    // 未支付
    public function scopeNopay($query)
    {
        return $query->where('status', self::STATUS_NOPAY);
    }

    // 未发货
    public function scopeNosend($query)
    {
        return $query
            ->whereHas('item', function (Builder $query) {
                $query
                    ->where('dispatch_status', \orderitemModel::DISPATCH_STATUS_NOSEND)
                    ->whereNotIn('refund_status', [\orderitemModel::REFUND_STATUS_OK, \orderitemModel::REFUND_STATUS_FINISH]);
            })
            ->whereDoesntHave('item', function (Builder $query) {
                $query
                    ->where('dispatch_status', \orderitemModel::DISPATCH_STATUS_NOSEND)
                    ->whereNotIn('refund_status', [\orderitemModel::REFUND_STATUS_OK, \orderitemModel::REFUND_STATUS_FINISH])
                    ->where('aftersale_status', \orderitemModel::AFTERSALE_STATUS_AFTERING);
            });

        // SELECT * FROM `cs_order`
        // WHERE EXISTS (
        //     SELECT * FROM `cs_order_item`
        //     WHERE `cs_order`.`id` = `cs_order_item`.`order_id`
        //     AND `dispatch_status` = 0
        //     AND `refund_status` NOT IN (2, 3)
        // )
        // AND NOT EXISTS (
        //     SELECT * FROM `cs_order_item`
        //     WHERE `cs_order`.`id` = `cs_order_item`.`order_id`
        //     AND `dispatch_status` = 0
        //     AND `refund_status` NOT IN (2, 3)
        //     AND `aftersale_status` = 1
        // )
        // AND `order_sn` = '202211265889335860009700'
        // LIMIT 1
    }

    // 待收货
    public function scopeNoget($query)
    {
        return $query
            ->whereHas('item', function (Builder $query) {
                $query
                    ->where('dispatch_status', \orderitemModel::DISPATCH_STATUS_SENDED)
                    ->whereNotIn('refund_status', [\orderitemModel::REFUND_STATUS_OK, \orderitemModel::REFUND_STATUS_FINISH]);
            });
    }


    // 待评价
    public function scopeNocomment($query)
    {
        return $query
            ->whereHas('item', function (Builder $query) {
                $query
                    ->where('dispatch_status', \orderitemModel::DISPATCH_STATUS_GETED)
                    ->where('comment_status', \orderitemModel::COMMENT_STATUS_NO)
                    ->whereNotIn('refund_status', [\orderitemModel::REFUND_STATUS_OK, \orderitemModel::REFUND_STATUS_FINISH]);
            });
    }

    // 售后 (后台要用，虽然有专门的售后单列表)
    public function scopeAftersale($query)
    {
        return $query
            ->whereHas('item', function (Builder $query) {
                $query->where('aftersale_status', '<>', \orderitemModel::AFTERSALE_STATUS_NOAFTER);
            });
    }

    // 退款 (即将废弃，有专门的售后单列表)
    public function scopeRefundStatus($query)
    {
        return $query
            ->whereHas('item', function (Builder $query) {
                $query->where('aftersale_status', '<>', \orderitemModel::REFUND_STATUS_NOREFUND);
            });
    }


    // 已支付
    public function scopePayed($query)
    {
        return $query->whereIn('status', [self::STATUS_PAYED, self::STATUS_FINISH]);
    }

    // 已完成
    public function scopeFinish($query)
    {
        return $query->where('status', self::STATUS_FINISH);
    }

    public function scopeCanAftersale($query)
    {
        return $query->whereIn('status', [self::STATUS_PAYED, self::STATUS_FINISH]);
    }

    public function scopeCanDelete($query)
    {
        return $query->whereIn('status', [
            self::STATUS_CANCEL,
            self::STATUS_INVALID,
            self::STATUS_FINISH
        ]);
    }



    // 门店订单 scope


    // 获取门店 id 条件
    private function getStoreWhere($store_id) {
        $where = [];

        if ($store_id == 'current') {
            // 默认手机商户端，取当前登陆的门店
            $store = Store::info();
            $where['store_id'] = $store['id'];
        } else {
            if ($store_id) {
                $where['store_id'] = $store_id;
            } else {
                $where['store_id'] = ['<>', 0];
            }
        }

        return $where;
    }

    /**
     * 全部订单
     */
    public function scopeStore($query, $store_id = 'current')
    {
        $where = $this->getStoreWhere($store_id);

        return $query->whereExists(function ($query) use ($where) {
            $order_table_name = (new self())->getQuery()->getTable();
            $table_name = (new \orderitemModel())->getQuery()->getTable();
            $query->table($table_name)->where('order_id=' . $order_table_name . '.id')->where($where);
        });
    }


    /**
     * 未发货
     */
    public function scopeStoreNosend($query, $store_id = 'current') {
        $where = [
            'dispatch_status' => \orderitemModel::DISPATCH_STATUS_NOSEND,
            'refund_status' => ['not in', [\orderitemModel::REFUND_STATUS_OK, \orderitemModel::REFUND_STATUS_FINISH]]       // 没有退款完成
        ];

        $where = array_merge($where, $this->getStoreWhere($store_id));

        return $query->whereExists(function ($query) use ($where) {
            $order_table_name = (new self())->getQuery()->getTable();
            $table_name = (new \orderitemModel())->getQuery()->getTable();
            $query->table($table_name)->where('order_id=' . $order_table_name . '.id')->where($where);
        });
    }


    /**
     * 未收货
     */
    public function scopeStoreNoget($query, $store_id = 'current') {
        $where = [
            'dispatch_status' => \orderitemModel::DISPATCH_STATUS_SENDED,
            'refund_status' => ['not in', [\orderitemModel::REFUND_STATUS_OK, \orderitemModel::REFUND_STATUS_FINISH]]       // 没有退款完成
        ];

        $where = array_merge($where, $this->getStoreWhere($store_id));

        return $query->whereExists(function ($query) use ($where) {
            $order_table_name = (new self())->getQuery()->getTable();
            $table_name = (new \orderitemModel())->getQuery()->getTable();
            $query->table($table_name)->where('order_id=' . $order_table_name . '.id')->where($where);
        });
    }


    // 待评价
    public function scopeStoreNocomment($query, $store_id = 'current')
    {
        $where = [
            'dispatch_status' => \orderitemModel::DISPATCH_STATUS_GETED,
            'refund_status' => ['not in', [\orderitemModel::REFUND_STATUS_OK, \orderitemModel::REFUND_STATUS_FINISH]],       // 没有退款完成
            'comment_status' => \orderitemModel::COMMENT_STATUS_NO
        ];

        $where = array_merge($where, $this->getStoreWhere($store_id));

        return $query->whereExists(function ($query) use ($where) {
            $order_table_name = (new self())->getQuery()->getTable();
            $table_name = (new \orderitemModel())->getQuery()->getTable();
            $query->table($table_name)->where('order_id=' . $order_table_name . '.id')->where($where);
        });
    }

    // 门店售后订单
    public function scopeStoreAftersale($query, $store_id = 'current')
    {
        $where = [
            'aftersale_status' => ['<>', \orderitemModel::AFTERSALE_STATUS_NOAFTER]
        ];

        $where = array_merge($where, $this->getStoreWhere($store_id));

        return $query->whereExists(function ($query) use ($where) {
            $order_table_name = (new self())->getQuery()->getTable();
            $table_name = (new \orderitemModel())->getQuery()->getTable();
            $query->table($table_name)->where('order_id=' . $order_table_name . '.id')->where($where);
        });
    }

    // 退款
    public function scopeStoreRefundStatus($query, $store_id = 'current')
    {
        $where = [
            'refund_status' => ['<>', \orderitemModel::REFUND_STATUS_NOREFUND],       // 只要申请过退款
        ];

        $where = array_merge($where, $this->getStoreWhere($store_id));

        return $query->whereExists(function ($query) use ($where) {
            $order_table_name = (new self())->getQuery()->getTable();
            $table_name = (new \orderitemModel())->getQuery()->getTable();
            $query->table($table_name)->where('order_id=' . $order_table_name . '.id')->where($where);
        });
    }


    /**
     * 已完成，这个只手机门店订单查询
     */
    public function scopeStoreFinish($query) {
        $store = Store::info();
        // 收完货就算已完成
        $where = [
            'store_id' => $store['id'],
            'dispatch_status' => \orderitemModel::DISPATCH_STATUS_GETED,
            'refund_status' => ['not in', [\orderitemModel::REFUND_STATUS_OK, \orderitemModel::REFUND_STATUS_FINISH]]       // 没有退款完成
        ];

        return $query->whereExists(function ($query) use ($where) {
            $order_table_name = (new self())->getQuery()->getTable();
            $table_name = (new \orderitemModel())->getQuery()->getTable();
            $query->table($table_name)->where('order_id=' . $order_table_name . '.id')->where($where);
        });
    }
}
